import {Message} from 'element-ui';
import createAxios from './axios.js';

export default () => {
    var util = new Object();

    util.browser = {
        language: (navigator.browserLanguage || navigator.language).toLowerCase(),
        runTime: () => {
            var u = navigator.userAgent;
            return {
                //移动终端浏览器版本信息
                trident: u.indexOf("Trident") > -1, //IE内核
                presto: u.indexOf("Presto") > -1, //opera内核
                webKit: u.indexOf("AppleWebKit") > -1, //苹果、谷歌内核
                gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") == -1, //火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf("Android") > -1 || u.indexOf("Linux") > -1, //android终端或uc浏览器
                iPhone: u.indexOf("iPhone") > -1, //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf("iPad") > -1, //是否iPad
                webApp: u.indexOf("Safari") == -1, //是否web应该程序，没有头部与底部
                wechat: u.toLowerCase().match(/MicroMessenger/i) == "micromessenger"
            };
        },
        getUrlParam: (name) => {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        }
    };

    // 转入外部资源
    util.source = [];
    // params {mode, url, name, resolve, reject}
    // mode = script / link
    util.loadSourceUrl = (params) => {
        var loadSource = function (x) {
            if (util.source[x.name]) {
                x.resolve();
                return;
            }
            ;

            if (x.mode == "script") {
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = x.url;
                script.onload = x.resolve;
                script.onerror = x.reject;
                script.setAttribute("remove", x.name);
                document.head.appendChild(script);
                util.source[x.name] = script;
            } else {
                var style = document.createElement("link");
                style.rel = "stylesheet";
                style.href = x.url;
                style.onload = x.resolve;
                style.onerror = x.reject;
                style.setAttribute("remove", x.name);
                document.head.appendChild(style);
                util.source[x.name] = style;
            }
        };

        if (typeof (params) == "array") {
            for (let x of params) {
                loadSource(x);
            }
        } else {
            loadSource(params);
        }
    };
    util.removeSourceOperate = (params) => {
        var removeSource = function (x) {
            var element = document.getElementsByTagName(x);
            for (let i = 0; i < element.length; i++) {
                if (element[i] && element[i].getAttribute("remove")) {
                    element[i].parentNode.removeChild(element[i]);
                }
            }
        };

        if (!params) {
            for (let x of ["script", "link"]) {
                removeSource(x);
            }
        }
    };

    // 请求数据集接口
    util.getRequestInterface = (path, params, callBack) => {
        var httpRequest = createAxios();

        httpRequest.get(path, {params}).then(
            (res) => {
                util.callBackSplitOperate(res, callBack);
            }
        ).catch(
            (frs) => {
                util.callBackSplitOperate(frs, callBack);
            }
        );
    };
    util.postRequestInterface = (path, params, callBack) => {
        var httpRequest = createAxios();

        httpRequest.post(path, params).then(
            (res) => {
                util.callBackSplitOperate(res, callBack);
            }
        ).catch(
            (frs) => {
                util.callBackSplitOperate(frs, callBack);
            }
        );
    };
    util.callBackSplitOperate = (data, callBack) => {
        var successCallBack = typeof (callBack) == 'function' ? callBack : callBack.success,
            failCallBack = callBack.fail || null,
            completeCallBack = callBack.complete || null,
            code = 0;

        if (data.code) code = Number(data.code);
        if (code === 200) {
            // console.log('axios', data);
            successCallBack(data);
        } else {
            if (failCallBack) {
                failCallBack(data);
            } else {
                if (data.msg) {

                    Message.info(data.msg || '操作失败');
                }

                util.defaultAbnormalSituation({
                    type: 'fail', event: 'console.print', location: 'http.request.return.fail',
                    result: data
                });
            }
        }

        if (completeCallBack) completeCallBack(data);
    };

    // 默认的失败执行处理操作
    util.defaultAbnormalSituation = (response) => {
        var type = response.type || false,
            jsonStr = JSON.stringify(response);

        if (type) {
            let result = JSON.stringify(response.result);

            switch (response.event) {
                case 'alert':
                    alert(response.location + "\n" + result);
                    break;
                case 'console.print':
                    console.log(response.location + "：", result);
                    break;
            }
        } else {
            console.log(jsonStr);
        }
    };

    return util;
};
